package com.huawei.fastengine.fastview.download.download;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.huawei.fastengine.R;
import com.huawei.fastengine.fastview.Config;
import com.huawei.fastengine.fastview.OpenFastAppEngine;
import com.huawei.fastengine.fastview.download.download.bean.DownloadRequest;
import com.huawei.fastengine.fastview.download.install.InstallProcess;
import com.huawei.fastengine.fastview.download.install.ManagerTask;
import com.huawei.fastengine.fastview.download.utils.ActivityUtil;
import com.huawei.fastengine.fastview.download.utils.CommonUtils;
import com.huawei.fastengine.fastview.download.utils.UiHelper;
import com.huawei.fastengine.fastview.download.utils.log.FastViewLogUtils;
import com.huawei.fastengine.fastview.startFastappEngine.bean.RpkInfo;
import com.huawei.fastengine.fastview.startFastappEngine.bean.RpkPageInfo;
import com.huawei.hms.support.hianalytics.HiAnalyticsConstant;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;
import o.ll;

@SuppressLint({"InflateParams"})
public class DownloadActivity extends Activity implements OnClickListener {
    public static final String ACTION_INSTALL_INFO_FAIL = "action_install_info_fail";
    public static final String INTENT_BUNDLE_KEY_RPK_LOADER_PAGE = "rpk_load_page";
    private static final String TAG = "DownloadActivity";
    private static final Map<String, String> downloadUrlMap = new HashMap();
    private final String PACKAGE_ADDED = "android.intent.action.PACKAGE_ADDED";
    private String callbackId = "";
    private AlertDialog dlCancelDialog;
    private AlertDialog dlProgressDialog;
    private DownloadAppHandler downloadAppHandler;
    private ProgressBar downloadProgressbar;
    private TextView downloadText;
    private GuideDownloadDlg guideDownloadDlg = new GuideDownloadDlg();
    private String mDetailUrl = "";
    private File mDownLoadFile;
    private InstallInfoReceiver mInstallInfoReceiver;
    private MyInstalledReceiver mInstalledReceiver;
    private DownloadManager mInstance;
    private RpkPageInfo mRpkpageinfo;

    class DialogOnKeyListener implements OnKeyListener {
        private DialogOnKeyListener() {
        }

        public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
            if (i != 4 || keyEvent.getAction() != 0) {
                return false;
            }
            if (DownloadActivity.this.dlCancelDialog != null && DownloadActivity.this.dlCancelDialog.isShowing()) {
                FastViewLogUtils.i(DownloadActivity.TAG, "click key back, cancel down dialog dismiss.");
                DownloadActivity.this.dlCancelDialog.dismiss();
                return true;
            } else if (DownloadActivity.this.dlProgressDialog == null || !DownloadActivity.this.dlProgressDialog.isShowing()) {
                FastViewLogUtils.i(DownloadActivity.TAG, "click key back, other case.");
                return false;
            } else {
                FastViewLogUtils.i(DownloadActivity.TAG, "click key back, down dialog dismiss.");
                DownloadActivity.this.showCancelDownloadDialog();
                return true;
            }
        }
    }

    class DownloadAppHandler extends Handler {
        private DownloadAppHandler() {
        }

        private void dealDownload(Message message) {
            switch (message.what) {
                case 1:
                    if (message.arg2 == 0) {
                        FastViewLogUtils.e("msg.arg2==0  ");
                        return;
                    }
                    int i = (int) ((((double) message.arg1) / ((double) message.arg2)) * 100.0d);
                    long j = (long) message.arg1;
                    if (i > 0) {
                        DownloadActivity.this.downloadProgressbar.setProgress(i);
                        float progress = ((float) DownloadActivity.this.downloadProgressbar.getProgress()) / ((float) DownloadActivity.this.downloadProgressbar.getMax());
                        int i2 = (int) (100.0f * progress);
                        CharSequence format = NumberFormat.getPercentInstance().format((double) progress);
                        FastViewLogUtils.e("download,", "progress_str " + format);
                        FastViewLogUtils.e("download,", "" + i + "/" + j + "/" + progress + "/" + i2);
                        DownloadActivity.this.downloadText.setText(format);
                        return;
                    }
                    return;
                case 3:
                    DownloadActivity.this.downloadProgressbar.setProgress(100);
                    CharSequence format2 = NumberFormat.getPercentInstance().format(1.0d);
                    FastViewLogUtils.e("download,", "downloaded progress_str " + format2);
                    DownloadActivity.this.downloadText.setText(format2);
                    InstallProcess.installProcess(DownloadActivity.this.getApplicationContext(), new ManagerTask(Config.FASTAPP_PACKAGE_NAME, message.getData().getString("path")));
                    return;
                case 4:
                    if (!ActivityUtil.isActivityDestroyed(DownloadActivity.this)) {
                        Toast.makeText(DownloadActivity.this, DownloadActivity.this.getString(R.string.fastapp_dl_install_failed), 0).show();
                        try {
                            DownloadActivity.this.dlProgressDialog.dismiss();
                        } catch (IllegalArgumentException e) {
                            FastViewLogUtils.d(DownloadActivity.TAG, "dlProgressDialog dismiss IllegalArgumentException");
                        }
                        DownloadActivity.this.finish();
                        FastViewLogUtils.i(DownloadActivity.TAG, "download activity on download failed.");
                        return;
                    }
                    return;
                default:
                    FastViewLogUtils.e(DownloadActivity.TAG, "Unkonw message " + message.what);
                    return;
            }
        }

        public void handleMessage(Message message) {
            dealDownload(message);
        }
    }

    class InstallInfoReceiver extends BroadcastReceiver {
        private InstallInfoReceiver() {
        }

        public void onReceive(Context context, Intent intent) {
            if (intent != null && !CommonUtils.hasParseException(intent)) {
                String action = intent.getAction();
                FastViewLogUtils.d(DownloadActivity.TAG, "action " + action);
                if ("action_install_info_fail".equals(action)) {
                    DownloadActivity.this.onInstallFailed();
                }
            }
        }
    }

    public class MyInstalledReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            if (intent != null && !CommonUtils.hasParseException(intent) && "android.intent.action.PACKAGE_ADDED".equals(intent.getAction())) {
                String dataString = intent.getDataString();
                FastViewLogUtils.i(DownloadActivity.TAG, "instal :" + dataString);
                if ("package:com.huawei.fastapp".equals(dataString)) {
                    DownloadActivity.this.onInstallSuccessed();
                }
            }
        }
    }

    private void registerReceiver() {
        this.mInstalledReceiver = new MyInstalledReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.PACKAGE_ADDED");
        intentFilter.addDataScheme(HiAnalyticsConstant.BI_KEY_PACKAGE);
        registerReceiver(this.mInstalledReceiver, intentFilter);
    }

    public static void setDownloadUrl(String str, String str2) {
        downloadUrlMap.put(str, str2);
    }

    private void showCancelDownloadDialog() {
        Builder builder = new Builder(this);
        builder.setMessage(R.string.fastapp_dl_cancel_download_prompt_ex);
        builder.setPositiveButton(R.string.fastapp_dl_sure_cancel_download, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                DownloadActivity.this.downloadProgressbar.setProgress(0);
                DownloadActivity.this.downloadProgressbar.setMax(0);
                DownloadActivity.this.downloadText.setText("");
                DownloadActivity.this.dlCancelDialog.dismiss();
                DownloadActivity.this.dlProgressDialog.dismiss();
                DownloadActivity.this.mInstance.stopDownload();
                if (!TextUtils.isEmpty(DownloadActivity.this.callbackId)) {
                    DownloadCallbackManager.getInstance().consume(DownloadActivity.this.callbackId, 1);
                }
                DownloadActivity.this.finish();
            }
        });
        builder.setNegativeButton(R.string.fastapp_exit_cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                DownloadActivity.this.dlCancelDialog.dismiss();
            }
        });
        this.dlCancelDialog = builder.create();
        this.dlCancelDialog.setOnKeyListener(new DialogOnKeyListener());
        this.dlCancelDialog.setCanceledOnTouchOutside(false);
        this.dlCancelDialog.show();
    }

    private void showDlProgressDialog() {
        FastViewLogUtils.e(TAG, "showDlProgressDialog");
        this.dlProgressDialog = new Builder(this).create();
        View inflate = LayoutInflater.from(this).inflate(R.layout.fastapp_progress_dialog, null);
        this.downloadProgressbar = (ProgressBar) inflate.findViewById(R.id.fastapp_third_app_dl_progressbar);
        this.downloadText = (TextView) inflate.findViewById(R.id.fastapp_third_app_dl_progress_text);
        inflate.findViewById(R.id.fastap_cancel_imageview).setOnClickListener(this);
        int dp2px = UiHelper.dp2px(this, 16);
        this.dlProgressDialog.setView(inflate, dp2px, 0, dp2px, 0);
        this.dlProgressDialog.setOnKeyListener(new DialogOnKeyListener());
        this.dlProgressDialog.setCanceledOnTouchOutside(false);
        FastViewLogUtils.e(TAG, "dlProgressDialog show");
        this.dlProgressDialog.show();
        this.downloadText.setText(NumberFormat.getPercentInstance().format(0.0d));
    }

    private void startDownload(String str, String str2) {
        FastViewLogUtils.d(TAG, RpkInfo.DOWNLOAD_URL + str + " / " + str2);
        DownloadRequest downloadRequest = new DownloadRequest();
        this.mInstance = DownloadManager.getInstance();
        downloadRequest.setUrl(str);
        downloadRequest.setNeedCheck(false);
        if (!TextUtils.isEmpty(str2)) {
            downloadRequest.setHash(str2);
        }
        this.mInstance.downloadAsyncOKHttp(downloadRequest, getApplicationContext(), new DownloadListener() {
            public void failure(int i) {
                FastViewLogUtils.e("DownloadManager failure,", i + "");
                if (4 != i) {
                    if (!TextUtils.isEmpty(DownloadActivity.this.callbackId)) {
                        DownloadCallbackManager.getInstance().consume(DownloadActivity.this.callbackId, 2);
                    }
                    Message message = new Message();
                    message.what = 4;
                    DownloadActivity.this.downloadAppHandler.sendMessage(message);
                } else if (!TextUtils.isEmpty(DownloadActivity.this.callbackId)) {
                    DownloadCallbackManager.getInstance().consume(DownloadActivity.this.callbackId, 1);
                }
            }

            public void progress(int i, int i2) {
                FastViewLogUtils.e("DownloadManager progress,", i + "/" + i2);
                Message message = new Message();
                message.what = 1;
                message.arg1 = i;
                message.arg2 = i2;
                DownloadActivity.this.downloadAppHandler.sendMessage(message);
            }

            public void success(File file) {
                DownloadActivity.this.mDownLoadFile = file;
                Message message = new Message();
                message.what = 3;
                Bundle bundle = new Bundle();
                String str = null;
                try {
                    str = file.getCanonicalPath();
                } catch (IOException e) {
                    FastViewLogUtils.e(DownloadActivity.TAG, "getCanonicalPath exception");
                }
                String str2 = "path";
                if (str == null) {
                    str = "";
                }
                bundle.putString(str2, str);
                message.setData(bundle);
                DownloadActivity.this.downloadAppHandler.sendMessage(message);
            }
        });
    }

    private void unregisterReceiver() {
        if (this.mInstalledReceiver != null) {
            unregisterReceiver(this.mInstalledReceiver);
            this.mInstalledReceiver = null;
        }
    }

    public void onClick(View view) {
        if (view.getId() == R.id.fastap_cancel_imageview && this.dlProgressDialog != null && this.dlProgressDialog.isShowing()) {
            FastViewLogUtils.i(TAG, "click key back, down dialog dismiss.");
            showCancelDownloadDialog();
        }
    }

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        Intent intent = getIntent();
        if (intent != null && !CommonUtils.hasParseException(intent)) {
            Serializable serializableExtra = intent.getSerializableExtra(INTENT_BUNDLE_KEY_RPK_LOADER_PAGE);
            if (serializableExtra != null && (serializableExtra instanceof RpkPageInfo)) {
                this.mRpkpageinfo = (RpkPageInfo) serializableExtra;
            }
            this.callbackId = intent.getStringExtra("callbackId");
            if (!TextUtils.isEmpty(this.callbackId)) {
                this.mDetailUrl = (String) downloadUrlMap.remove(this.callbackId);
            }
            if (TextUtils.isEmpty(this.mDetailUrl)) {
                if (!TextUtils.isEmpty(this.callbackId)) {
                    DownloadCallbackManager.getInstance().consume(this.callbackId, 2);
                }
                finish();
                return;
            }
            this.guideDownloadDlg.showGuideDownloadDlg(this, new Callback() {
                public void onNegative() {
                    DownloadActivity.this.finish();
                    if (!TextUtils.isEmpty(DownloadActivity.this.callbackId)) {
                        DownloadCallbackManager.getInstance().consume(DownloadActivity.this.callbackId, 1);
                    }
                }

                public void onPositive() {
                    DownloadActivity.this.downloadAppHandler = new DownloadAppHandler();
                    DownloadActivity.this.startDownload(DownloadActivity.this.mDetailUrl, "");
                    DownloadActivity.this.showDlProgressDialog();
                }
            });
            registerReceiver();
            this.mInstallInfoReceiver = new InstallInfoReceiver();
            ll.ˏ(this).ˏ(this.mInstallInfoReceiver, new IntentFilter("action_install_info_fail"));
        }
    }

    protected void onDestroy() {
        FastViewLogUtils.e(TAG, "onDestroy");
        unregisterReceiver();
        ll.ˏ(this).ˋ(this.mInstallInfoReceiver);
        if (this.mInstance != null) {
            this.mInstance.resetDownload();
        }
        this.guideDownloadDlg.dismissGuideDownloadDlg();
        super.onDestroy();
    }

    public void onInstallFailed() {
        FastViewLogUtils.i(TAG, "install failed.");
        Toast.makeText(this, getString(R.string.fastapp_dl_install_failed), 0).show();
        if (this.dlProgressDialog != null) {
            this.dlProgressDialog.dismiss();
        }
        if (this.mInstance != null) {
            DownloadManager downloadManager = this.mInstance;
            DownloadManager.deleteFile(this.mDownLoadFile);
        }
        finish();
        if (!TextUtils.isEmpty(this.callbackId)) {
            DownloadCallbackManager.getInstance().consume(this.callbackId, 2);
        }
    }

    public void onInstallSuccessed() {
        FastViewLogUtils.i(TAG, "onInstallSuccessed :");
        if (!ActivityUtil.isActivityDestroyed(this)) {
            if (this.mInstance != null) {
                DownloadManager downloadManager = this.mInstance;
                DownloadManager.deleteFile(this.mDownLoadFile);
            }
            if (this.dlProgressDialog != null) {
                try {
                    this.dlProgressDialog.dismiss();
                } catch (IllegalArgumentException e) {
                    FastViewLogUtils.d(TAG, "dlProgressDialog dismiss IllegalArgumentException");
                }
            }
            if (this.dlCancelDialog != null) {
                try {
                    this.dlCancelDialog.dismiss();
                } catch (IllegalArgumentException e2) {
                    FastViewLogUtils.d(TAG, "dlCancelDialog dismiss IllegalArgumentException");
                }
            }
            if (this.mRpkpageinfo != null) {
                FastViewLogUtils.d(TAG, "openFastAppFromDownload");
                OpenFastAppEngine.getInstance().openFastAppFromDownload(this.mRpkpageinfo);
            }
            finish();
            if (!TextUtils.isEmpty(this.callbackId)) {
                DownloadCallbackManager.getInstance().consume(this.callbackId, 0);
            }
        }
    }

    protected void onResume() {
        super.onResume();
        FastViewLogUtils.e(TAG, "onResume");
    }
}
